<template>
    <view class="login-container">
        <!-- 头部Logo -->
        <view class="login-header">
            <text class="login-title">京东登录注册</text>
        </view>

        <!-- 登录表单 -->
        <view class="login-form">
            <!-- 手机号输入框 -->
            <view class="input-group">
                <view class="prefix">+86</view>
                <input type="number" class="phone-input" v-model="phoneNumber" placeholder="请输入手机号" maxlength="11"
                    @input="handlePhoneInput" />
            </view>

            <!-- 验证码输入框 -->
            <view class="input-group verify-group">
                <input type="number" class="verify-input" v-model="verifyCode" placeholder="请输入收到的验证码" maxlength="6" />
                <button class="get-verify-btn" :disabled="!canGetVerify || isCounting" @click="getVerifyCode">
                    {{ isCounting ? `${countDown}s` : '获取验证码' }}
                </button>
            </view>

            <!-- 登录按钮 -->
            <button class="login-btn" :disabled="!canLogin" @click="submitLogin">
                同意协议并登录
            </button>

            <!-- 其他登录方式 -->
            <view class="other-login">
                <text class="password-login" @click="gotoPasswordLogin">账号密码登录</text>
                <text class="other-methods" @click="showOtherMethods">其他登录方式</text>
            </view>

            <!-- 协议勾选 -->
            <view class="agreement">
<<<<<<< HEAD
                <checkbox class="agreement-check" :checked="agreeProtocol" @change="handleAgreeChange" color="#e43130" />
=======
                <checkbox class="agreement-check" v-model="agreeProtocol" color="#e43130" />
>>>>>>> 130a1ee47851a7f86a508259a249ec75bc9e6d2d
                <text class="agreement-text">
                    我已阅读并同意《京东用户协议》《用户隐私政策》，未注册的手机号将自动创建京东账号
                </text>
            </view>

            <!-- 第三方登录 -->
            <view class="third-party" v-if="showThirdParty">
                <view class="third-title">其他登录方式</view>
                <view class="third-icons">
                    <view class="third-icon" @click="loginWithWechat">
                        <uni-icons type="weixin" size="36" color="#07C160"></uni-icons>
                        <text>微信登录</text>
                    </view>
                    <view class="third-icon" @click="loginWithQQ">
                        <uni-icons type="qq" size="36" color="#12B7F5"></uni-icons>
                        <text>QQ登录</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { requestQueue } from '@/api/requestQueue.js'
export default {
    data() {
        return {
            phoneNumber: '', // 手机号
            verifyCode: '', // 验证码
            agreeProtocol: false, // 是否同意协议
            isCounting: false, // 是否正在倒计时
            countDown: 60, // 倒计时秒数
            showThirdParty: false // 是否显示第三方登录
        };
    },
     computed: {
    // 是否可以获取验证码
    canGetVerify() {
      return /^1[3-9]\d{9}$/.test(this.phoneNumber) && this.agreeProtocol;
    },
    // 是否可以登录
    canLogin() {
      return this.phoneNumber && this.verifyCode && this.agreeProtocol;
    }
  },
   methods: {
    // 处理手机号输入
    handlePhoneInput(e) {
      this.phoneNumber = e.detail.value.replace(/\D/g, ''); // 只保留数字
    },
    
    // 处理协议勾选
    handleAgreeChange(e) {
      this.agreeProtocol = e.detail.value.length > 0;
    },

    // 获取验证码
    getVerifyCode() {
      if (!this.canGetVerify) return;

      // 调用获取验证码接口（加入请求队列）
      requestQueue.addTask(() => {
        return new Promise((resolve, reject) => {
          uni.request({
            url: 'https://plogin.m.jd.com/cgi-bin/mobile/LoginGetVerifyCode',
            method: 'POST',
            data: {
              mobile: this.phoneNumber,
              appid: 300,
              returnurl: encodeURIComponent('https://m.jd.com/?sceneval=2&appCode=ms0ca95114')
            },
            header: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Referer': 'https://plogin.m.jd.com/login/login?appid=300&returnurl=https%3A%2F%2Fm.jd.com%2F%3Fsceneval%3D2%26appCode%3Dms0ca95114'
            },
            success: (res) => {
              console.log('验证码请求结果:', res.data);
              if (res.data.success) {
                uni.showToast({ title: '验证码已发送', icon: 'none' });
                this.startCountDown();
                resolve(res);
              } else {
                uni.showToast({ title: res.data.msg || '获取验证码失败', icon: 'none' });
                reject(res);
              }
            },
            fail: (err) => {
              console.error('验证码请求失败:', err);
              uni.showToast({ title: '网络错误', icon: 'none' });
              reject(err);
            }
          });
        });
      });
    },

    // 开始倒计时
    startCountDown() {
      this.isCounting = true;
      const timer = setInterval(() => {
        this.countDown--;
        if (this.countDown <= 0) {
          clearInterval(timer);
          this.isCounting = false;
          this.countDown = 60;
        }
      }, 1000);
    },

    // 提交登录
    submitLogin() {
      if (!this.canLogin) return;

      // 调用登录接口（加入请求队列）
      requestQueue.addTask(() => {
        return new Promise((resolve, reject) => {
          uni.request({
            url: 'https://plogin.m.jd.com/cgi-bin/mobile/LoginSubmit',
            method: 'POST',
            data: {
              mobile: this.phoneNumber,
              code: this.verifyCode,
              appid: 300,
              returnurl: encodeURIComponent('https://m.jd.com/?sceneval=2&appCode=ms0ca95114'),
              loginType: 2
            },
            header: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Referer': 'https://plogin.m.jd.com/login/login?appid=300&returnurl=https%3A%2F%2Fm.jd.com%2F%3Fsceneval%3D2%26appCode%3Dms0ca95114'
            },
            success: (res) => {
              console.log('登录结果:', res.data);
              if (res.data.success) {
                // 登录成功，保存token并跳转
                uni.setStorageSync('token', res.data.token);
                uni.setStorageSync('userInfo', res.data.userInfo);
                
                // 跳转回原页面（从URL参数获取）
                const pages = getCurrentPages();
                const currentPage = pages[pages.length - 1];
                const { redirect } = currentPage.options;
                
                if (redirect) {
                  uni.redirectTo({ url: `/${redirect}` });
                } else {
                  uni.switchTab({ url: '/pages/index/index' });
                }
                resolve(res);
              } else {
                uni.showToast({ title: res.data.msg || '登录失败', icon: 'none' });
                reject(res);
              }
            },
            fail: (err) => {
              console.error('登录请求失败:', err);
              uni.showToast({ title: '网络错误', icon: 'none' });
              reject(err);
            }
          });
        });
      });
    },

    // 跳转到密码登录
    gotoPasswordLogin() {
      uni.navigateTo({ url: '/pages/login/password' });
    },

    // 显示其他登录方式
    showOtherMethods() {
      this.showThirdParty = !this.showThirdParty;
    },

    // 微信登录
    loginWithWechat() {
      // 调用微信登录API
      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          // 微信登录成功后，调用京东的微信登录接口
          requestQueue.addTask(() => {
            return new Promise((resolve) => {
              uni.request({
                url: 'https://plogin.m.jd.com/cgi-bin/mobile/WechatLogin',
                method: 'POST',
                data: {
                  code: loginRes.code,
                  appid: 300
                },
                success: (res) => {
                  console.log('微信登录结果:', res.data);
                  // 处理登录结果（同上）
                  resolve(res);
                }
              });
            });
          });
        }
      });
    },

    // QQ登录
    loginWithQQ() {
      // 类似微信登录逻辑
      uni.login({
        provider: 'qq',
        success: (loginRes) => {
          // 调用京东QQ登录接口
          console.log('QQ登录code:', loginRes.code);
        }
      });
    }
  }
};</script>


<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #fff;
  padding: 0 20rpx;
}

.login-header {
  padding: 60rpx 0;
  text-align: center;
}

.login-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.login-form {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.input-group {
  display: flex;
  align-items: center;
  height: 90rpx;
  border-bottom: 1px solid #eee;
  margin-bottom: 10rpx;
}

.prefix {
  font-size: 30rpx;
  color: #666;
  margin-right: 20rpx;
}

.phone-input, .verify-input {
  flex: 1;
  height: 100%;
  font-size: 30rpx;
  padding: 0;
}

.verify-group {
  justify-content: space-between;
}

.get-verify-btn {
  width: 200rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 26rpx;
  color: #e43130;
  background-color: transparent;
  border: none;
  padding: 0;
  margin: 0;
}

.get-verify-btn:disabled {
  color: #999;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  color: #fff;
  background-color: #e43130;
  border-radius: 45rpx;
  margin-top: 60rpx;
  border: none;
}

.login-btn:disabled {
  background-color: #f29595;
}

.other-login {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
  padding: 0 20rpx;
}

.password-login, .other-methods {
  font-size: 26rpx;
  color: #666;
}

.agreement {
  display: flex;
  align-items: center;
  margin-top: 80rpx;
  font-size: 24rpx;
  color: #999;
}

.agreement-check {
  transform: scale(0.8);
  margin-right: 10rpx;
}

.agreement-text {
  line-height: 1.5;
}

.third-party {
  margin-top: 60rpx;
}

.third-title {
  text-align: center;
  font-size: 26rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.third-icons {
  display: flex;
  justify-content: center;
  gap: 60rpx;
}

.third-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.third-icon text {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}
</style>